<template>
  <div class="progress-container">
    <div class="progress-wrap" ref="progressWrap">
      <div class="progress" :style="percent">
        <div
          @touchstart="handleStart"
          @touchend="handleEnd"
          class="circle"
          ref="circle"
        ></div>
      </div>
    </div>
    <p class="currentTime">{{ formatSeconds(getSongMsg.currentTime) }}</p>
    <p class="duration">{{ formatSeconds(getSongMsg.duration / 1000) }}</p>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { formatSeconds } from "../utils/timeFormate";
export default {
  props: ["myAudio"],
  data() {
    return {
      audio: this.myAudio,
      startClientX: null,
      startPointMsg: {},
      progressWidth: 0,
      dragPercent: 0,
      ifDrag: false,
    };
  },
  computed: {
    ...mapGetters(["getSongCurrentTime", "getSongMsg"]),
    percent() {
      let { currentTime, duration } = this.getSongMsg;
      let percent = (currentTime / (duration / 1000)) * 100;
      if (!this.ifDrag) {
        return {
          width: percent + "%",
        };
      } else {
        this.$nextTick(() => {
          this.ifDrag = false;
          this.myAudio.currentTime =
            ((duration / 1000) * this.dragPercent) / 100;
          return {
            width: this.dragPercent + "%",
          };
        });
      }
    },
  },
  methods: {
    formatSeconds(val) {
      return formatSeconds(val);
    },
    handleStart(e) {
      //记录初始点xy
      let { clientX } = e.changedTouches[0];
      this.startClientX = clientX;
    },
    handleEnd(e) {
      console.log(e);
      // 记录结束点
      let { clientX } = e.changedTouches[0];
      //dragPercent 通过移动后的circle的(clientX-左边offset距离)除progress-wrap的宽度来算出
      this.dragPercent = Number(
        Number(
          ((clientX - this.$refs.progressWrap.offsetLeft) /
            this.progressWidth) *
            100
        ).toFixed(1)
      );
      this.ifDrag = true;
    },
  },
  mounted() {
    this.progressWidth =
      window.innerWidth - this.$refs.progressWrap.offsetLeft * 2; //一边的offset 所以要乘2
  },
};
</script>

<style lang="less" scoped>
@import url("../assets/Drag-progress/index.less");
</style>